//
//  F_UserAuthenticationVC.swift
//  letuofu
//
//  Created by dooland2 on 2020/3/7.
//  Copyright © 2020 WH-JS. All rights reserved.
//

import UIKit

class F_UserAuthenticationVC: BaseViewControllerWithHeader {
    let nameLab = UILabel()
    let textFieldID = TextField()
    let textFieldCard = TextField()
    let textFieldPhone = TextField()
    let textFieldCode = TextField()
    let timerBtn = Button()
    let tipsLab = UILabel()
    
    let xieyiBtn = Button()
    let card_xieyiBtn = Button()

    var smsVerifyCredential = ""
    var timeCount = 60
    var timer : Timer?
    let lineT = UIView()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        setupUI()
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */
    
    func timerinvalidate() {
        timer?.invalidate()
        timer = nil
        print("\(self)已销毁")
    }
    
    func nameAuthentication(callback: @escaping (Bool,[String:Any?]) -> Void) {
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "",
                                    "userName": nameLab.text ?? "",
                                    "IDCardNo": textFieldID.text ?? "",
                                    "bankCardMobile": textFieldPhone.text ?? "",
                                    "bankCardNo": textFieldCard.text ?? "",
                                    "vaildeCode": textFieldCode.text ?? "",
                                    "smsVerifyCredential": smsVerifyCredential]
        API.request(url: .F_NameAuthentication, params: params) { (result) in
            if result.success {
               if let dl = result.data?.getDictionary("data") {
                callback(result.success,dl)
               }
            }else{
                callback(false,[String:Any?]())
            }
        }
    }
    
    func financeAccountSendVerifyCode(callback: @escaping ([String:Any?]) -> Void) {
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "",
                                    "smsUsesCode": "110004",
                                    "mobile": textFieldPhone.text ?? ""]
        API.request(url: .F_FinanceAccountSendVerifyCode, params: params) { (result) in
            if result.success {
               if let dl = result.data?.getDictionary("data") {
                callback(dl)
               }
            }else{
                let popup = PopupBox(infoText: "发送失败")
                popup.show(vc: UIViewController.topMostController() ?? self)
            }
        }
    }
}

// MARK: UI
extension F_UserAuthenticationVC {
    func setupUI() {
        scrollView.backgroundColor = .white
        safeView.backgroundColor = .xF2F2F2
        headView.backgroundColor = .white
        headTitle.text = "实名认证"
        
        //画横线
        var line = scrollView.drawView { (make) in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview()
            make.height.equalTo(1)
        }
        line.backgroundColor = .xF2F2F2
        
        var lab = scrollView.drawLabel(text: "实名认证", fontSize: 24, textColor: .x333333) { (make) in
            make.top.equalTo(10)
            make.left.equalTo(23)
            make.right.equalTo(20)
        }
        
        lab = scrollView.drawLabel(text: "填写信息只做数据校验，APP不留存身份证信息、 银行卡信息等数据！", fontSize: 14, textColor: .x666666) { (make) in
            make.top.equalTo(lab.snp.bottom).offset(17)
            make.left.equalToSuperview().offset(23)
            make.right.equalToSuperview().offset(-38)
            make.height.equalTo(36)
        }
        lab.numberOfLines = 2
        
        scrollView.drawLabel(label: nameLab, text: nameLab.text, fontSize: 15, textColor: .x333333) { (make) in
            make.top.equalTo(lab.snp.bottom).offset(21)
            make.left.equalToSuperview().offset(23)
            make.right.equalToSuperview().offset(-38)
        }
        let dl = LocalStorage.getDic(forKey: USER_INFO)
        nameLab.text = dl?.getString("name")
        lab = scrollView.drawLabel(text: "如信息有误请提交书面到企业人事部进行信息修改。", fontSize: 10, textColor: .x333333) { (make) in
            make.top.equalTo(nameLab.snp.bottom).offset(7)
            make.left.equalToSuperview().offset(23)
            make.right.equalToSuperview().offset(-38)
        }
        
        //画横线
        line = scrollView.drawView { (make) in
            make.top.equalTo(lab.snp.bottom).offset(10)
            make.left.equalToSuperview().offset(23)
            make.right.equalToSuperview().offset(-23)
            make.height.equalTo(1)
        }
        line.backgroundColor = .xF2F2F2
        
        scrollView.drawTextField(textField: textFieldID, placeholder: "请输入您的身份证号码", fontSize: 15, keyboardType:.numberPad){ (make) in
            make.top.equalTo(line.snp.bottom).offset(25)
            make.left.equalToSuperview().offset(23)
            make.right.equalToSuperview().offset(-23)
        }
        
        //画横线
        line = scrollView.drawView { (make) in
            make.top.equalTo(textFieldID.snp.bottom).offset(10)
            make.left.equalToSuperview().offset(23)
            make.right.equalToSuperview().offset(-23)
            make.height.equalTo(1)
        }
        line.backgroundColor = .xF2F2F2
        
        scrollView.drawTextField(textField: textFieldCard, placeholder: "请输入您的借记卡号", fontSize: 15, keyboardType:.numberPad){ (make) in
            make.top.equalTo(line.snp.bottom).offset(25)
            make.left.equalToSuperview().offset(23)
            make.right.equalToSuperview().offset(-23)
        }
        
        //画横线
        line = scrollView.drawView { (make) in
            make.top.equalTo(textFieldCard.snp.bottom).offset(10)
            make.left.equalToSuperview().offset(23)
            make.right.equalToSuperview().offset(-23)
            make.height.equalTo(1)
        }
        line.backgroundColor = .xF2F2F2
        
        scrollView.drawTextField(textField: textFieldPhone, placeholder: "请输入卡号预留电话", fontSize: 15, keyboardType:.numberPad){ (make) in
            make.top.equalTo(line.snp.bottom).offset(25)
            make.left.equalToSuperview().offset(23)
            make.right.equalToSuperview().offset(-23)
        }
        
        //画横线
        line = scrollView.drawView { (make) in
            make.top.equalTo(textFieldPhone.snp.bottom).offset(10)
            make.left.equalToSuperview().offset(23)
            make.right.equalToSuperview().offset(-23)
            make.height.equalTo(1)
        }
        line.backgroundColor = .xF2F2F2
        
        scrollView.drawTextField(textField: textFieldCode, placeholder: "请输入验证码", fontSize: 15, keyboardType:.numberPad){ (make) in
            make.top.equalTo(line.snp.bottom).offset(25)
            make.left.equalToSuperview().offset(23)
            make.right.equalToSuperview().offset(-23)
        }
        
        //画横线
        line = scrollView.drawView { (make) in
            make.top.equalTo(textFieldCode.snp.bottom).offset(10)
            make.left.equalToSuperview().offset(23)
            make.right.equalToSuperview().offset(-23)
            make.height.equalTo(1)
        }
        line.backgroundColor = .xF2F2F2
        
        scrollView.drawButton(button: timerBtn,title: "获取验证码", titleColor: .x333333, fontSize: 15) { (make) in
            make.right.equalToSuperview().offset(-23)
            make.top.equalTo(textFieldCode.snp.top)
        }
        timerBtn.hitEdgInsets = .init(top: -20, left: -20, bottom: -20, right: -20)
        timerBtn.addTarget(self, action: #selector(onTimerButtonClick(button:)), for: .touchUpInside)
        
        //画横线
        scrollView.drawView(view: lineT) { (make) in
            make.top.equalTo(timerBtn.snp.bottom).offset(5)
            make.left.equalTo(timerBtn)
            make.right.equalTo(timerBtn)
            make.height.equalTo(1)
        }
        lineT.backgroundColor = .x333333
        
        scrollView.drawLabel(label: tipsLab, text: "", fontSize: 14, textColor: .red){ (make) in
            make.top.equalTo(line.snp.bottom).offset(7)
            make.left.equalTo(line.snp.left)
        }
        
        scrollView.drawButton(button: xieyiBtn,imageNamed: "f_unselect") { (make) in
            make.top.equalTo(line.snp.bottom).offset(48)
            make.left.equalTo(23)
        }
        xieyiBtn.setImage(UIImage.init(named: "f_select"), for: .selected)
        xieyiBtn.hitEdgInsets = .init(top: -10, left: -10, bottom: -10, right: -5)
        xieyiBtn.addTarget(self, action: #selector(xieyiButtonClick(button:)), for: .touchUpInside)
        
        lab = scrollView.drawLabel(text: "同意《实名认证协议》", fontSize: 14, textColor: .x333333) { (make) in
            make.centerY.equalTo(xieyiBtn)
            make.left.equalTo(xieyiBtn.snp.right).offset(5)
        }
        lab.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(_shimingTap(tap:))))
        lab.isUserInteractionEnabled = true
        
        scrollView.drawButton(button: card_xieyiBtn,imageNamed: "f_unselect") { (make) in
            make.top.equalTo(line.snp.bottom).offset(72)
            make.left.equalTo(23)
        }
        card_xieyiBtn.setImage(UIImage.init(named: "f_select"), for: .selected)
        card_xieyiBtn.hitEdgInsets = .init(top: -10, left: -10, bottom: -10, right: -5)
        card_xieyiBtn.addTarget(self, action: #selector(cxieyiButtonClick(button:)), for: .touchUpInside)
        
        lab = scrollView.drawLabel(text: "同意《绑定银行卡到大账户协议》", fontSize: 14, textColor: .x333333) { (make) in
            make.centerY.equalTo(card_xieyiBtn)
            make.left.equalTo(card_xieyiBtn.snp.right).offset(5)
        }
        lab.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(_yinhangTap(tap:))))
        lab.isUserInteractionEnabled = true
        
        scrollView.drawLabel(text: "请阅读并同意《实名认证协议》才能进行下一步", fontSize: 14, textColor: .red){ (make) in
            make.top.equalTo(card_xieyiBtn.snp.bottom).offset(10)
            make.left.equalTo(line.snp.left)
        }
        
        let btn = scrollView.drawButton(title: "下一步", titleColor: .white, fontSize: 15) { (make) in
            make.top.equalTo(card_xieyiBtn.snp.bottom).offset(50)
            make.centerX.equalToSuperview()
            make.left.equalToSuperview().offset(30)
            make.right.equalToSuperview().offset(-30)
            make.height.equalTo(35)
        }
        btn.backgroundColor = .xFC4C02
        btn.layer.cornerRadius = 7
        btn.addTarget(self, action: #selector(onOKButtonClick(button:)), for: .touchUpInside)
        scrollView.bottomEqualTo(btn)
        
        initKeyboardObserver()
        fillAccessoryToolBar()
    }
}


// MARK: 事件
extension F_UserAuthenticationVC {
    func codeTimer() {
        if timer != nil {
            return
        }
        timer=Timer.scheduledTimer(timeInterval:1, target:self, selector:#selector(functickDown), userInfo:nil, repeats:true)
        //开始计时器
        timeCount = 60
        timer?.fire()
    }
    
    //打开实名协议
    @objc func _shimingTap(tap:UITapGestureRecognizer){
        let vc = M_SimpleArticleVC()
        pushViewController(vc)
        vc.loadUrl("https://cw.51camel.com/appweb/agreement3.html")
        vc.headTitle.text = "实名认证协议"
    }
    
    //打开银行协议
    @objc func _yinhangTap(tap:UITapGestureRecognizer){
        let vc = M_SimpleArticleVC()
        pushViewController(vc)
        vc.loadUrl("https://cw.51camel.com/appweb/agreement4.html")
        vc.headTitle.text = "绑定银行卡到大账户协议"
    }
    
    @objc func functickDown(){
        print("0timeCount\(timeCount)")
        if timeCount > 0 {
            timerBtn.isEnabled = false
            timerBtn.setTitleAndColor(title: "重新发送(\(String(describing: timeCount)))", color: .x999999)
            lineT.backgroundColor = .x999999
            timeCount-=1
        }
        else {
            //消除计时器（页面释放是必须调用这个方法，不让会让页面和定时器不会释放）
            timerBtn.isEnabled = true
            timerBtn.setTitleAndColor(title: "获取验证码", color: .x333333)
            lineT.backgroundColor = .x333333
            timerinvalidate()
        }
    }
    
    @objc func xieyiButtonClick(button:UIButton){
        xieyiBtn.isSelected = !xieyiBtn.isSelected
    }
    
    @objc func cxieyiButtonClick(button:UIButton){
        card_xieyiBtn.isSelected = !card_xieyiBtn.isSelected
    }
    
    @objc func onTimerButtonClick(button:UIButton){
        if !(textFieldPhone.text?.validateMobile() ?? false) {
            tipsLab.text = "手机号码不规范，请重新输入"
            let popup = PopupBox(infoText: "手机号码不规范，请重新输入")
            popup.show(vc: UIViewController.topMostController() ?? self)
            return
        }
        financeAccountSendVerifyCode(callback: { (data) in
            self.smsVerifyCredential = data.getString("smsVerifyCredential") ?? ""
            self.codeTimer()
        })
    }
    
    @objc func onOKButtonClick(button:UIButton){
        if !(textFieldPhone.text?.validateMobile() ?? false) {
            tipsLab.text = "手机号码不规范，请重新输入"
            let popup = PopupBox(infoText: "手机号码不规范，请重新输入")
            popup.show(vc: UIViewController.topMostController() ?? self)
            return
        } else if !(xieyiBtn.isSelected && card_xieyiBtn.isSelected) {
            return
        }
        else {
            nameAuthentication(callback: { (succeed,data) in
                if succeed {
                    let vc = F_SucceedVC()
                    self.pushViewController(vc)
                }
                else {
                    let vc = F_FailVC()
                    self.pushViewController(vc)
                }
            })
        }
        
    }
}
